package cn.jlearn.proxy.agent.listener;

import cn.jlearn.proxy.agent.AgentStartApp;
import cn.jlearn.proxy.agent.container.ProxyClient;
import cn.jlearn.proxy.common.body.ClientConnectSuccessBody;
import cn.jlearn.proxy.common.enums.MsgTypeEnum;
import cn.jlearn.proxy.common.packet.BsPacket;
import cn.jlearn.proxy.common.pojo.Constant;
import cn.jlearn.proxy.common.utils.NetUtil;
import cn.jlearn.proxy.common.utils.PropertiesUtil;
import com.alibaba.fastjson.JSON;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;

import java.util.Collections;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/5/10 6:13 下午
 */
public class ProxyClientListener implements ClientAioListener {

    private final String host = PropertiesUtil.getProperty("server.host");

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        if (isConnected) {
            Tio.bindBsId(channelContext, AgentStartApp.TOKEN);

            ClientConnectSuccessBody body = new ClientConnectSuccessBody(AgentStartApp.TOKEN, AgentStartApp.DOMAIN,
                    channelContext.getId());
            BsPacket bsPacket = new BsPacket(MsgTypeEnum.TCP_CLIENT_CONNECT_SUCCESS_REQ.getCode(), JSON.toJSONBytes(body));
            Tio.sendToBsId(ProxyClient.clientTioConfig, AgentStartApp.TOKEN, bsPacket);

            String url = String.format(host + Constant.API_GET_CHANNEL_INFO, AgentStartApp.TOKEN);
            NetUtil.doPost(url, JSON.toJSONString(Collections.singletonMap("online", "Y")));
        }
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {

    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {

    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {

    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {

    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        String token = AgentStartApp.TOKEN;
        String url = String.format(host + Constant.API_GET_CHANNEL_INFO, token);
        NetUtil.doPost(url, JSON.toJSONString(Collections.singletonMap("online", "N")));
    }

}
